import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mobile_vpn/common/cpn/cpn_view_state.dart';
import 'package:mobile_vpn/common/ext/asset_ext.dart';
import 'package:mobile_vpn/pages/set_up/set_logic.dart';
import 'package:url_launcher/url_launcher.dart'; // 导入 url_launcher
import '../../common/cpn/sliver_app_bar.dart';
import '../../theme/color_palettes.dart';

class ContactServicePage extends CpnViewState<SetLogic> {

  ContactServicePage({Key? key}) : super(key: key, bindViewState: false);
  BuildContext? _context;
  OverlayEntry? _overlayEntry;

  // 客服配置数据
  final List<Map<String, dynamic>> serviceContacts = [
    {
      'type': 'QQ',
      'number': '123456789',
      'time': '工作日 9:00-18:00',
      'scopes': ['产品咨询', '技术支持', '售后服务']
    },
    {
      'type': '微信',
      'number': 'service_account',
      'time': '7x24小时',
      'scopes': ['紧急支持', '合作洽谈', 'VIP服务']
    }
  ];

  @override
  Widget buildBody(BuildContext context) {
    _context = context;
    return CustomScrollView(
      slivers: [
        // 调用公共 SliverAppBar
        commonSliverAppBar(
          title: "联系客服",
        ),
        // 将原有 ListView 转换为 SliverList
        SliverList(
          delegate: SliverChildListDelegate(
            serviceContacts.map((contact) {
              return _buildContactCard(contact);
            }).toList(),
          ),
        )
      ],
    );
  }

  Widget _buildContactCard(Map<String, dynamic> contact) {
    return GestureDetector(
      onTap: () => _launchApp(contact['type'], contact['number']),
      child: Card(
        color: ColorPalettes.instance.background,
        margin: EdgeInsets.only(top: 30.h),
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15.r),
        ),
        child: Padding(
          padding: EdgeInsets.all(30.h),
          child: Column(
            children: [
              // 客服类型图标
              Row(
                children: [
                  contact['type'] == 'QQ'
                      ? Image(
                          image: AssetImage("qq".png),
                          width: 50.w,
                          height: 50.h,
                        )
                      : Image(
                          image: AssetImage("weichat".png),
                          width: 50.w,
                          height: 50.h,
                        ),
                  SizedBox(width: 15.w),
                  Text(
                    '${contact['type']}客服',
                    style: TextStyle(
                      fontSize: 38.sp,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF000000),
                    ),
                  )
                ],
              ),
              SizedBox(height: 25.h),
              // 联系方式
              _buildContactInfo(contact),
              SizedBox(height: 25.h),
              // 服务时间
              _buildServiceTime(contact['time'] as String),
              SizedBox(height: 25.h),
              // 提示信息
              _buildHintText(contact['type'])
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildContactInfo(Map<String, dynamic> contact) {
    return Row(
      children: [
        Icon(Icons.contact_phone,
            size: 40.w, color: ColorPalettes.instance.primary),
        SizedBox(width: 10.w),
        Expanded(
          child: Text(
            '${contact['type']}号码: ${contact['number']}',
            style: TextStyle(
              fontSize: 30.sp,
              color: ColorPalettes.instance.secondText,
            ),
          ),
        ),
        Icon(
          Icons.content_copy,
          size: 35.w,
          color: ColorPalettes.instance.primary,
        )
      ],
    );
  }

  Widget _buildServiceTime(String time) {
    return Row(
      children: [
        Icon(
          Icons.access_time,
          size: 40.w,
          color: ColorPalettes.instance.primary,
        ),
        SizedBox(width: 10.w),
        Text(
          time,
          style: TextStyle(
            fontSize: 30.sp,
            color: ColorPalettes.instance.secondText,
          ),
        )
      ],
    );
  }

  Widget _buildHintText(String type) {
    String hint = '';
    switch (type) {
      case 'QQ':
        hint = '如果点击卡片无法唤起QQ，请手动复制添加';
        break;
      case '微信':
        hint = '如果点击卡片无法唤起微信，请手动复制添加';
        break;
      default:
        hint = '如果点击卡片无法唤起应用，请手动复制添加';
    }

    return Row(
      children: [
        Icon(
          Icons.info,
          size: 40.w,
          color: ColorPalettes.instance.primary,
        ),
        SizedBox(width: 10.w),
        Text(
          hint,
          style: TextStyle(
            fontSize: 28.sp,
            color: ColorPalettes.instance.secondText,
          ),
        ),
      ],
    );
  }

  void _launchApp(String type, String number) async {
    final Uri uri;

    try {
      switch (type) {
        case 'QQ':
          // 确保 number 是有效的 QQ 号码（数字）
          if (!RegExp(r'^\d+$').hasMatch(number)) {
            throw Exception('无效的 QQ 号码');
          }
          uri = Uri.parse(
              'mqqwapi://card/show_psl_card?src_type=internal&version=1&uin=$number&card_type=person');
          break;

        case '微信':
          // 微信支持更多参数，例如预设消息内容
          uri = Uri.parse(
              'weixin://dl/chat?text=${Uri.encodeComponent(' 你好！我想加你为好友')}');
          break;

        default:
          throw Exception('不支持的应用类型');
      }

      // 检查应用是否已安装
      bool isInstalled = await canLaunchUrl(uri);
      if (!isInstalled) {
        throw Exception('未安装目标应用');
      }

      // 显示 Loading 状态
      showLoadingIndicator();

      if (!await launchUrl(uri)) {
        throw Exception('启动应用失败');
      }
    } catch (e) {
      print('Error: $e');
      _showAlertDialog('提示', '无法启动应用，请手动添加好友', _context!);
      _copyText(number);
    } finally {
      // 隐藏 Loading 状态
      hideLoadingIndicator();
    }
  }

  void showLoadingIndicator() {
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(
        builder: (context) => Container(
          color: Colors.black.withOpacity(0.5),
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ),
      );
      Overlay.of(_context!)?.insert(_overlayEntry!);
    }
  }

  void hideLoadingIndicator() {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
      _overlayEntry = null;
    }
  }

  void _copyText(String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(_context!).showSnackBar(
      SnackBar(
        content: Text('已复制: $text'),
        backgroundColor: ColorPalettes.instance.primary,
      ),
    );
  }
}

void _showAlertDialog(
    String title, String content, BuildContext context) async {
  await showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: <Widget>[
          TextButton(
            child: const Text('确定'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
